import Axios from 'axios';
import Jsonp from 'jsonp';

/* eslint-disable no-magic-numbers */
/* eslint-disable no-console */
const getHeaders = headers => Object.assign({
	'X-PPD-APPID': '10080084',
	'X-PPD-TIMESTAMP': new Date().getTime(),
	'X-PPD-DEVICEID': Math.round(Math.random() * Math.pow(10, 15)).toString(10),
	'X-PPD-KEY': 'tc-059',
	'X-PPD-KEYVERSION': '1',
	'X-PPD-SIGNVERSION': '1',
	'X-PPD-APPVERSION': '2.1.0',
	'X-PPD-M-PRODUCTLINE': '1',
	'X-PPD-APPOS': '2',
	'X-PPD-M-PRODUCTID': '3',
	'X-PPD-M-AID': '903f41c545ac40d1b296a4b75383a37f',
	'X-PPD-SIGN': ''
}, headers);

export default {
	install(Vue, options) {
		Vue.$get = Vue.prototype.$get = (url, params) => {
			const headers = getHeaders();

			return Axios
				.get(url, {
					headers,
					'timeout': 20000,
					params
				})
				.then(res => res.data)
				.catch(err => console.error(err));
		};

		Vue.$post = Vue.prototype.$post = (url, params) => {
			const headers = getHeaders();

			return Axios
				.post(url, params, {
					headers,
					'timeout': 20000
				})
				.then(res => res.data)
				.catch(err => console.error(err));
		};

		Vue.$jsonp = Vue.prototype.$jsonp = (url, params) =>
			new Promise((resolve, reject) =>
				Jsonp(`${url}?${Object.entries(params).map(([key, val]) => `${key}=${val}`).join('&')}`, {
					'timeout': 20000
				}, (err, data) => {
					if (err) {
						console.error(err.message);
						reject(err);
					} else {
						resolve(data);
					}
				}));
	}
};
